<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>创建直播订阅</title>
    <link rel="stylesheet" href="https://image.v1.vodeshop.com/element-index.css">
    {{--    <link rel="stylesheet" href="/css/element.css">--}}
    <link rel="stylesheet" href="/css/liveSubscription/editlivesubscribe.css">
    <style>
        #editlivesubscribe .w-e-menu {
            z-index: 100 !important;
        }

        #editlivesubscribe .w-e-text-container {
            z-index: 100 !important;
        }
    </style>
</head>

<body>
<div id="editlivesubscribe">
    <div class="shopHeader" style="padding-right: 20px">
        <span></span>
        <a href="{{route('live-subscription.index')}}" id="editlivesubscribeListId"><i
                class="el-icon-s-unfold"></i>列表</a>
    </div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="170px" class="demo-ruleForm">
        <div class="editlivesubscribe-centent">
            <el-form-item label="主播ID" prop="user_id">
                <div>
                    <div>
                        <el-input placeholder="请输入主播ID" v-model="ruleForm.user_id">
                            <template slot="prepend"><i class="el-icon-edit"></i></template>
                        </el-input>
                    </div>
                    <div class="bottom-text">
                        <i class="el-icon-info"></i>用户ID
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input placeholder="请输入标题" v-model="ruleForm.title">
                    <template slot="prepend"><i class="el-icon-edit"></i></template>
                </el-input>
            </el-form-item>
            <el-form-item label="主播开始时间" prop="live_time">
                <el-date-picker v-model="ruleForm.live_time" type="datetime" placeholder="选择主播开始时间"
                                default-time="12:00:00"
                                :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="直播订阅封面图" required>
                <div>
                    <el-button type="primary" @click="addSurfaceImgBtn" size="mini">
                        @{{ruleForm.surface === '' ? '上传订阅封面' : '更新订阅封面'}}
                    </el-button>
                    <input type="file" value="" class="choose" ref="surfaceImgObjFile" @change="onSurfaceImg">
                </div>
                <div class="dangeimgbox" v-if="ruleForm.surface">
                    <img :src="imgUrl + ruleForm.surface" alt="">
                </div>
            </el-form-item>
            <el-form-item label="推荐类型选择" prop="subscription_type">
                <el-radio-group v-model="ruleForm.subscription_type" @change="typeArdioFn">
                    <el-radio :label="1">商品</el-radio>
                    <el-radio :label="2">活动</el-radio>
                    <el-radio :label="3">会员</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="请选择内容">
                <div v-if="ruleForm.subscription_type === 1">
                    <el-select v-model="crowd_fund_Arr" multiple filterable remote reserve-keyword
                               placeholder="请输入商品关键词"
                               :remote-method="remoteMethod">
                        <el-option v-for="item in goodsOptions" :key="item.id" :label="item.text" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div v-if="ruleForm.subscription_type === 2">
                    <el-select v-model="crowd_fundVal" filterable remote placeholder="请输入活动关键词"
                               :remote-method="remoteActMethod">
                        <el-option v-for="item in actOptions" :key="item.id" :label="item.text" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-form-item>
        </div>
        <el-form-item label="详情视频">
            <div>
                <input type="file" value="" ref="noticeObjFile" @change="onNotice">
                <el-button type="danger" size="mini" @click="reomveVideoBtn" v-if="ruleForm.video != ''">删除视频
                </el-button>
            </div>
            <div v-if="ruleForm.video != ''">
                <video :src="imgUrl + ruleForm.video" controls="controls" style="max-height: 425px;"></video>
            </div>
        </el-form-item>
        <el-form-item label="详情图片" required>
            <div class="main-img-box">
                <div class="imgbox-son" v-for="(item,inx) in ruleForm.images" :key="inx">
                    <img :src="imgUrl + item" alt="" class="img-center">
                    <div class="img-tab-box">
                        <el-button type="primary" icon="el-icon-search" circle size="mini" title="查看图片"
                                   @click="checkMainImg(item)"></el-button>
                        <el-button type="warning" icon="el-icon-delete" circle size="mini" title="删除图片"
                                   @click="reomveMainImg(inx)"></el-button>
                    </div>
                </div>
                <div class="imgbox-son add-img" @click="addMainBtn" title="添加图片">
                    <div class="upimg">
                        <i class="el-icon-upload" style="font-size: 66px;color: #666;"></i>
                    </div>
                </div>
            </div>
            <input type="file" value="" class="choose" ref="mainImgObjFile" @change="onMainImg">
        </el-form-item>
        <el-form-item label="分享图片" required>
            <div class="main-img-box">
                <div class="imgbox-son" v-for="(item,inx) in ruleForm.share_images" :key="inx">
                    <img :src="imgUrl + item" alt="" class="img-center">
                    <div class="img-tab-box">
                        <el-button type="primary" icon="el-icon-search" circle size="mini" title="查看图片"
                                   @click="checkMainImg(item)"></el-button>
                        <el-button type="warning" icon="el-icon-delete" circle size="mini" title="删除图片"
                                   @click="reomveShareImg(inx)"></el-button>
                    </div>
                </div>
                <div class="imgbox-son add-img" @click="addShareBtn" title="添加图片">
                    <div class="upimg">
                        <i class="el-icon-upload" style="font-size: 66px;color: #666;"></i>
                    </div>
                </div>
            </div>
            <input type="file" value="" class="choose" ref="shareImgObjFile" @change="onShareImg">
        </el-form-item>
        <div class="editlivesubscribe-centent">
            <el-form-item label="假订阅数量">
                <el-input-number v-model="ruleForm.fake_collect" :step="1" :min="0" :max="9999999"
                                 step-strictly></el-input-number>
            </el-form-item>
            <el-form-item label="假粉丝数量">
                <el-input-number v-model="ruleForm.fake_fans_num" :step="1" :min="0" step-strictly></el-input-number>
            </el-form-item>
            <el-form-item label="排序">
                <el-input-number v-model="ruleForm.sort" :step="1" :min="0" step-strictly></el-input-number>
            </el-form-item>
            <el-form-item label="直播状态">
                <el-radio-group v-model="ruleForm.status">
                    <el-radio :label="0">取消开播</el-radio>
                    <el-radio :label="1">正常开播</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="上架状态">
                <el-radio-group v-model="ruleForm.up">
                    <el-radio :label="0">下架</el-radio>
                    <el-radio :label="1">上架</el-radio>
                </el-radio-group>
            </el-form-item>
        </div>
        <el-form-item label="详情">
            <!-- 富文本编辑器的容器 -->
            <div id="editlivesubscribeeditor">
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提 交</el-button>
        </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="imgUrl + dialogImageUrl" alt="">
    </el-dialog>
</div>
<script src="/js/liveSubscription/vue.min.js"></script>
<script src="/js/liveSubscription/axios.min.js"></script>
<script src="/js/liveSubscription/element.min.js"></script>
<script type="text/javascript">
    var histNum = sessionStorage.getItem("subscriptionpage") ? sessionStorage.getItem("subscriptionpage") : 0
    var histUrl = sessionStorage.getItem("subscriptionpagehist") ? sessionStorage.getItem("subscriptionpagehist") : window.location.href
    if (histNum == 0) {
        sessionStorage.setItem("subscriptionpage", 1)
        history.go(0)
    }
    var setInterOff = setInterval(() => {
        if (histUrl != window.location.href) {
            sessionStorage.removeItem("subscriptionpage")
            sessionStorage.removeItem("subscriptionpagehist")
            clearInterval(setInterOff)
        }
    }, 1000)
</script>
<script src="/js/liveSubscription/wangEditor.min.js"></script>
<script src="/js/liveSubscription/api.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#editlivesubscribe',
        data: {
            baseUrl: '/',
            imgUrl: 'https://image.v1.vodeshop.com/', // 显示图片前缀域名路径
            videoUrl: 'https://video.v1.vodeshop.com/', // 显示视频前缀域名路径
            goodsOptions: [],
            actOptions: [],
            merchantArr: [],
            integralArr: [],
            dialogVisible: false,
            dialogImageUrl: '',
            ruleForm: {
                user_id: '', // 主播id
                title: '', // 标题
                surface: '', // 直播订阅封面图
                video: '', // 预告视频
                images: [], // 主图
                share_images: [], // 分享图
                list_chart: '', // 活动列表图
                sort: 0, // 排序
                subscription_type: 1, // 推荐类型选择 1:商品 2：活动 3：会员
                fake_fans_num: 0,
                fake_collect: 0,
                content: '',
                subscription_json: null, // 请选择内容
                status: 1,
                up: 1,
                live_time: null, // 开播时间
            },
            crowd_fund_Arr: [], // 请选择内容数据赋值 --- 商品情况下是数组
            crowd_fundVal: '', // 请选择内容数据赋值 --- 活动情况下是对象
            rules: {
                user_id: [
                    {required: true, message: '请输入主播id', trigger: 'blur'}
                ],
                title: [
                    {required: true, message: '请输入标题', trigger: 'blur'},
                    {max: 50, message: '标题最长50个字符', trigger: 'blur'}
                ],
                subscription_type: [
                    {required: true, message: '请选择推荐类型选择', trigger: 'change'}
                ],
                live_time: [
                    {required: true, message: '请选择开播时间', trigger: 'change'}
                ]
            },
            pickerOptions: { // 众筹开始时间
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                }
            },
            endAtPickerOptions: { // 众筹结束时间
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                }
            },
        },
        created() {
            if (window.location.host == "love.test") {
                this.baseUrl = "http://love.test/"
                //baseUrl:'http://love.test/', // 获取后台数据前缀域名路径
            } else if (window.location.host == "test.api.vodeshop.com") { // 测试中
                this.baseUrl = "https://test.api.vodeshop.com/"
            } else { // 正式
                this.baseUrl = "https://api.vodeshop.com/"
            }
            this.init()
            let crowdId = window.location.href.split("/")[window.location.href.split("/").length - 2]
            this.getInfo(crowdId)
        },
        mounted() {
            var E = window.wangEditor
            this.editor = new E('#editlivesubscribeeditor')
            this.editor.customConfig.showLinkImg = false
            // 自定义上传图片
            this.editor.customConfig.customUploadImg = (files, insert) => {
                files.forEach(val => {
                    this.qinuiToken(val, '456', (res) => {
                        insert(this.imgUrl + res.hash)
                    })
                })
            }
            // 将图片大小限制为 3M
            this.editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
            // 限制一次最多上传 5 张图片
            this.editor.customConfig.uploadImgMaxLength = 5;
            this.editor.create()
            this.editor.txt.html('')
        },
        computed: {},
        methods: {
            init() {
                getGoodsList('').then(res => {
                    this.goodsOptions = res.data
                })
            },
            getInfo(id) {
                getSubscriptionInfo(id).then(res => {
                    console.log(res.data.data, '456456')
                    if (res.data.code === 0) {
                        let newData = res.data.data.data
                        newData['video'] = ''
                        newData['images'] = []
                        newData.media_json.forEach(v => {
                            if (v.type === 0) {
                                newData.images.push(v.src)
                            } else if (v.type === 1) {
                                newData.video = v.src
                            }
                        })
                        this.ruleForm = newData
                        // this.ruleForm['video'] = ''
                        // this.ruleForm['images'] = []
                        this.ruleForm.live_time = new Date(newData.live_time)
                        // this.ruleForm['id'] = id
                        this.editor.txt.html(newData.content)
                        if (newData.subscription_type === 2) {
                            this.crowd_fundVal = res.data.data.crowd_fund_arr.id
                            this.actOptions = [res.data.data.crowd_fund_arr]
                        }
                        if (newData.subscription_type === 1) {
                            this.goodsOptions = res.data.data.crowd_fund_arr
                            res.data.data.crowd_fund_arr.forEach(v => {
                                this.crowd_fund_Arr.push(v.id)
                            })
                        }
                    }
                    // goodsOptions: [],
                    //     actOptions: [],
                    // crowd_fund_Arr: [], // 请选择内容数据赋值 --- 商品情况下是数组
                    //     crowd_fundVal: '', // 请选择内容数据赋值 --- 活动情况下是对象
                })
            },
            typeArdioFn(val) { // 单选框点击事件
                this.crowd_fund_Arr = []
                this.crowd_fundVal = ''
                if (val === 1) {
                    getGoodsList('').then(res => {
                        this.goodsOptions = res.data
                    })
                } else {
                    getActList('').then(res => {
                        this.actOptions = res.data
                    })
                }
            },
            remoteMethod(val) {
                getGoodsList(val).then(res => {
                    this.goodsOptions = res.data
                })
            },
            remoteActMethod(val) {
                getActList(val).then(res => {
                    this.actOptions = res.data
                })
            },
            // 上传预告视频
            onNotice(e) {
                let file = e.target.files[0] || e.dataTransfer.files[0]
                console.log(file.type, file.size)
                if (file.type != 'video/mp4') {
                    this.$notify.warning({
                        title: '警告',
                        message: '仅支持上传mp4格式的视频'
                    });
                    return false
                }
                if (file.size / 1024 / 1024 > 50) {
                    this.$notify.warning({
                        title: '警告',
                        message: '视频不能大于50M'
                    });
                    return false
                }
                this.qinuiToken(file, 'videofile', params => {
                    console.log(this.ruleForm)
                    this.ruleForm.video = params.hash
                    console.log(this.ruleForm.video)
                    this.$refs.noticeObjFile.value = ''
                })
            },
            reomveVideoBtn() {
                this.ruleForm.video = ''
                this.ruleForm.video_cover = ''
            },
            // 上传视频封面
            addSurfaceImgBtn() {
                this.$refs.surfaceImgObjFile.click()
            },
            onSurfaceImg(e) {
                let file = e.target.files[0] || e.dataTransfer.files[0]
                this.qinuiToken(file, 'imgfile', params => {
                    this.ruleForm.surface = params.hash
                    this.$refs.surfaceImgObjFile.value = ''
                })
            },
            // 上传活动列表图
            addListImgBtn() {
                this.$refs.listImgObjFile.click()
            },
            removeListImgBtn() {
                this.ruleForm.list_chart = ''
            },
            onListImg(e) {
                let file = e.target.files[0] || e.dataTransfer.files[0]
                this.qinuiToken(file, 'imgfile', params => {
                    this.ruleForm.list_chart = params.hash
                    this.$refs.listImgObjFile.value = ''
                })
            },
            // 上传详情图片
            addMainBtn() {
                this.$refs.mainImgObjFile.click()
            },
            onMainImg(e) {
                let file = e.target.files[0] || e.dataTransfer.files[0]
                this.qinuiToken(file, 'imgfile', params => {
                    this.ruleForm.images.push(params.hash)
                    this.$refs.mainImgObjFile.value = ''
                })
            },
            reomveMainImg(inx) {
                this.ruleForm.images.splice(inx, 1)
            },
            // 分享图片
            addShareBtn() {
                this.$refs.shareImgObjFile.click()
            },
            onShareImg(e) {
                let file = e.target.files[0] || e.dataTransfer.files[0]
                this.qinuiToken(file, 'imgfile', params => {
                    this.ruleForm.share_images.push(params.hash)
                    this.$refs.shareImgObjFile.value = ''
                })
            },
            reomveShareImg(inx) {
                this.ruleForm.share_images.splice(inx, 1)
            },
            checkMainImg(val) {
                this.dialogVisible = true
                this.dialogImageUrl = val
            },
            // 上传文件处理
            qinuiToken(files, domref, fun) {
                let _that = this
                const axiosInstance = axios.create({withCredentials: false});    //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
                axiosInstance({
                    method: 'GET',
                    url: this.baseUrl + 'api/qiniu-uptoken'
                }).then(res => {
                    let formData = new FormData();
                    formData.append('token', res.data.uptoken);//七牛需要的token，叫后台给，是七牛账号密码等组成的hash
                    formData.append('file', files);
                    axiosInstance({
                        method: 'POST',
                        url: 'https://up-z2.qiniup.com/', //上传地址
                        data: formData,
                        timeout: 30000,//超时时间，因为图片上传有可能需要很久
                    }).then(function (success) {
                        fun(success.data) // 回调所获取的值
                        //上传成功，把input的value设置为空，不然 无法两次选择同一张图片
                        //上传成功(登录七牛账号，找到七牛给你的 URL地址) 和 data里面的key 拼接成图片下载地址
                    }).catch(function (err) {
                        //上传失败
                    });
                })
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let liveTime = new Date(this.ruleForm.live_time).getTime()
                        if (this.ruleForm.images.length === 0 || this.ruleForm.share_images.length === 0 || this.ruleForm.surface === '') {
                            this.$notify.warning({
                                title: '警告',
                                message: '请检查有没有上传详情图或者分享图片以及直播订阅封面图'
                            });
                            return false
                        }
                        let newObj = JSON.parse(JSON.stringify(this.ruleForm))
                        newObj.live_time = liveTime / 1000
                        if (this.ruleForm.subscription_type === 1) { // 选择类型是商品
                            console.log(this.goodsOptions, this.crowd_fund_Arr)
                            newObj.subscription_json = this.crowd_fund_Arr
                        } else if (this.ruleForm.subscription_type === 2) {// 选择类型是活动
                            if (this.crowd_fundVal === '') {
                                this.$notify.warning({
                                    title: '警告',
                                    message: '活动类型必须要选择'
                                });
                                return false
                            }
                            let actObj = this.actOptions.find(v => v.id === this.crowd_fundVal)
                            newObj.subscription_json = actObj
                        }
                        newObj.content = this.editor.txt.html()
                        editSubscriptionAdd(newObj).then(res => {
                            console.log(res, 999999999)
                            if (res.data.code === 0) {
                                this.$notify.success({
                                    title: '成功',
                                    message: res.data.msg
                                });
                                setTimeout(() => {
                                    document.getElementById("editlivesubscribeListId").click()
                                }, 1000)
                            }else{
                                this.$notify.error({
                                    title: '失败',
                                    message: res.data.msg
                                });
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
        },
    })
</script>
</body>

</html>
